﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace Fingerbrisk.DataSource.FluentDatasourceInteract.SqlServer
{
    public class SqlSource : IFluentSource
    {
        private readonly SqlConnection _connection;
        internal SqlConnection Connection
        {
            get { return _connection; }
        }

        public SqlSource(SqlConnection sqlConnection)
        {
            if (sqlConnection == null)
                throw new Exception("Could not create SqlSource with null SqlConnection");

            _connection = sqlConnection;
            _connection.Open();
        }

        #region IFluentSource Members

        public ConnectionState State
        {
            get { return Connection.State; }
        }

        public ITransaction NewTransaction()
        {
            return new SqlTransaction(this);
        }

        public IQueryExpression QueryAs()
        {
            return QueryWith(NewTransaction());
        }

        public IQueryExpression QueryWith(ITransaction transaction)
        {
            return new SqlQueryExpression(transaction);
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            Connection.Close();
        }

        #endregion
    }
}